using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;

namespace Web.Ajax.Controls
{
    //The base class for non composite controls
	public class WebControl : System.Web.UI.WebControls.WebControl, IJavascriptControl
    {
        public void RenderProperty(HtmlTextWriter writer, string Name, object Value)
        {
            string json = Json.ConvertToJson(Value, false);

            writer.WriteLine(JavascriptId + "." + Name + "=" + json + ";");
        }

        public void RenderJavascriptStartTag(HtmlTextWriter writer)
        {
            writer.WriteLine("<script type=\"text/javascript\" >");            
        }
        public void RenderJavascriptEndTag(HtmlTextWriter writer)
        {
            writer.Write("</script>");
        }

        public void RenderJavascriptId(HtmlTextWriter writer)
        {
			return;
            if (!string.IsNullOrEmpty(JavascriptId))
                writer.WriteLine("var " + JavascriptId + "=" + JavascriptId + ";");
        }

        public new Web.Ajax.Page Page
        {
            get
            {
                return base.Page as Web.Ajax.Page;
            }
            set
            {
                base.Page = value;
            }
        }

        private string javascriptId;
        public string JavascriptId
        {
            get 
			{
				if (string.IsNullOrEmpty(javascriptId))
					return ClientID;
				return javascriptId; 
			}
            set { javascriptId = value; }
        }

		public static string GetJavascriptId(Control c)
		{
			if (c == null)
				return null;
			if (c is IJavascriptControl)
			{
				return ((IJavascriptControl)c).JavascriptId;
			}
			else
				return c.ClientID;
		}

		public static string GetAttributeString(System.Web.UI.WebControls.WebControl c)
		{
			var s=" ";
			foreach (var key in c.Attributes.Keys)
			{
				var v=c.Attributes[key.ToString()];
				if(v==null)
					continue;
				s += key;
				s += "=\"";
				s += v.ToString();
				s += "\"";
				s += " ";
			}
			return s;
		}
    }
}
